﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using NNS.Framework;
using NNS.UI;
using QLTB.BusinessLayer;
using QLTB.BusinessObjects;
using QLTB.Common;
using QLTB.ThanhLyOrder.Entity.dsCanThanhLyTableAdapters;
using QLTB.ThanhLyOrder.UI;
using QLTB.ThietBi.Entity;
using QLTB.DataAccess;

namespace QLTB.ThanhLy.UI
{
    [System.ComponentModel.ToolboxItem(false)]
    public partial class ucThanhLyOder : MyUIBase
    {
        private GridHitInfo downhitInfo;
        private DataTable dtTL;

        public ucThanhLyOder()
        {
            InitializeComponent();
            gbList.BestFitColumns();
            NapInf();
            txtDonvi.EditValue = MyLogin.Original.iddonvi;
            if (!MyLogin.Original.toantinh)
            {
                txtDonvi.Enabled = false;
                txtDonvi.EditValue = MyLogin.Original.iddonvi;
            }

            TBL_quyenBL.IgnoreError = true;
            if (!TBL_quyenBL.isTaomoi(EnumComponent.iRequestLiquidation))
            {
                btnAllRight.Visible = false;
                btnRight.Visible = false;
            }
            TBL_quyenBL.IgnoreError = false;
        }

        private void view_MouseDown(object sender, MouseEventArgs e)
        {
            //GridView view = sender as GridView;
            //downhitInfo = null;
            //GridHitInfo hitInfo = view.CalcHitInfo(new Point(e.X, e.Y));
            //if (Control.ModifierKeys != Keys.None) return;
            //downhitInfo = gbList.CalcHitInfo(new Point(e.X, e.Y));
            //if (e.Button == MouseButtons.Left && hitInfo.RowHandle >= 0)
            //{
            //    downhitInfo = hitInfo;
            //}
        }

        private void view_MouseMove(object sender, MouseEventArgs e)
        {
            //GridView view = sender as GridView;
            //if (e.Button == System.Windows.Forms.MouseButtons.Left && downhitInfo != null)
            //{
            //    Size dragSize = SystemInformation.DragSize;
            //    Rectangle dragRect = new Rectangle(new Point(downhitInfo.HitPoint.X - dragSize.Width / 2, downhitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
            //    if (!dragRect.Contains(new Point(e.X, e.Y)))
            //    {
            //        if (downhitInfo.RowHandle >= 0)
            //        {
            //            DataRow row = view.GetDataRow(downhitInfo.RowHandle);
            //            view.GridControl.DoDragDrop(row, DragDropEffects.Move);
            //            downhitInfo = null;
            //            DevExpress.Utils.DXMouseEventArgs.GetMouseArgs(e).Handled = true;
            //        }
            //    }
            //}
        }


        //</gridControl1>

        public void Nap()
        {
            try
            {
                NotSave = false;
                tBL_THIETBITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                if (txtDonvi.EditValue != null)
                    tBL_THIETBITableAdapter.FillByTL(dsThietBi.TBL_THIETBI, txtDonvi.EditValue as int?);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Yêu cầu thanh lý");
            }
        }

        public void NapInf()
        {
            try
            {
                tBL_DONVITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_DONVITableAdapter.Fill(dsDonVi.TBL_DONVI);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Yêu cầu thanh lý");
            }
            NapCTL();
        }

        public void NapCTL()
        {
            try
            {
                if (dtTL != null) dtTL.RowChanged -= dtTL_RowChanged;
                tBL_THIETBITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                gcDesc.DataSource = dtTL = tBL_THIETBITableAdapter.GetDataByCTL(txtDonvi.EditValue as int?);
                dtTL.RowChanged += dtTL_RowChanged;
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Yêu cầu thanh lý");
            }
        }

        private void dtTL_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            NotSave = true;
        }

        private void txtDonvi_EditValueChanged(object sender, EventArgs e)
        {
            Nap();
            NapCTL();
        }

        private void Grid_DragOver(object sender, DragEventArgs e)
        {
            //if (e.Data.GetDataPresent(typeof(ThietBi.Entity.dsThietBi.TBL_THIETBIRow)))
            //{
            //    e.Effect = DragDropEffects.Move;
            //}
            //else
            //    e.Effect = DragDropEffects.None;
        }

        private void Grid_DragDrop(object sender, DragEventArgs e)
        {
            //GridControl grid = sender as GridControl;
            //DataTable table = grid.DataSource as DataTable;
            //if (table == null)
            //{
            //    table = dsThietBi.TBL_THIETBI;
            //}
            //DataRow row = e.Data.GetData(typeof(ThietBi.Entity.dsThietBi.TBL_THIETBIRow)) as DataRow;

            //if (row != null && table != null && row.Table != table)
            //{
            //    table.ImportRow(row);
            //    row.Delete();
            //}
        }

        private void gbList_DoubleClick(object sender, EventArgs e)
        {
            //GridControl grid = sender as GridControl;
            var table = gcDesc.DataSource as DataTable;
            int[] rows = gbList.GetSelectedRows();
            for (int i = rows.Length; i > 0; i--)
            {
                DataView dv;
                dv = gbDesc.DataSource as DataView;
                DataRow dr = gbList.GetDataRow(rows[i - 1]);
                dv.RowFilter = "ID=" + dr["ID"];
                if (dv.Count == 0)
                {
                    table.ImportRow(dr);
                    gbList.DeleteRow(rows[i - 1]);
                }
                dv.RowFilter = "";
            }
        }

        private void view_DoubleClick(object sender, EventArgs e)
        {
            var view = sender as GridView;
            var table = view.DataSource as DataTable;
            int[] rows = gbList.GetSelectedRows();
            for (int i = rows.Length; i > 0; i--)
            {
                DataView dv;
                dv = gbDesc.DataSource as DataView;
                DataRow dr = gbList.GetDataRow(rows[i - 1]);
                dv.RowFilter = "ID=" + dr["ID"];
                if (dv.Count == 0)
                {
                    table.ImportRow(dr);
                }
                gbList.DeleteRow(rows[i - 1]);
                dv.RowFilter = "";
            }
        }


        private void view_Delete(object sender, KeyEventArgs e)
        {
            if (!TBL_quyenBL.isThaydoi(EnumComponent.iRequestLiquidation))
            {
                return;
            }

            var view = sender as GridView;
            if (e.KeyCode == Keys.Delete)
            {
                view.DeleteSelectedRows();
            }
            else if (e.KeyData == (Keys.Control | Keys.Enter))
            {
                if (view == gbList)
                {
                    gbList_DoubleClick(gbList, e);
                }
                else
                {
                    gbDesc_DoubleClick(gbDesc, e);
                }
            }
            else if (e.KeyData == (Keys.Control | Keys.Right))
            {
                gbList_DoubleClick(gbList, e);
            }
            else if (e.KeyData == (Keys.Control | Keys.Left))
            {
                gbDesc_DoubleClick(gbDesc, e);
            }
        }

        public override void Save()
        {
            Enabled = false;
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                dsThietBi.TBL_THIETBIDataTable dt = dsThietBi.TBL_THIETBI;
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    DataRow dr = dt.Rows[i];
                    if (dr.RowState != DataRowState.Deleted)
                    {
                        SqlHelper.Helper.ExecuteNonQuery(CommandType.Text,
                                                         "update TBL_THIETBI set TinhTrang=3 where ID=@ID",
                                                         new[] {new SqlParameter("@ID", dr["ID"]),});
                    }
                    //else if (dr.RowState==DataRowState.Deleted)
                    //{
                    //    SqlHelper.Helper.ExecuteNonQuery(CommandType.Text, "update TBL_THIETBI set TinhTrang=3 where ID=@ID",
                    //                                     new[] { new SqlParameter("@ID", dr["ID",DataRowVersion.Original]), });
                    //}

                    OnSaveChanging(new SaveChangingEventArgs(i, dt.Count));
                }

                if (dtTL != null)
                    for (int i = 0; i < dtTL.Rows.Count; i++)
                    {
                        DataRow dr = dtTL.Rows[i];
                        if (dr.RowState != DataRowState.Deleted)
                        {
                            //MyBox.ShowInfo(dr["ID"].ToString(), "ta");
                            SqlHelper.Helper.ExecuteNonQuery(CommandType.Text,
                                                             "update TBL_THIETBI set TinhTrang=4 where ID=@ID",
                                                             new[] {new SqlParameter("@ID", dr["ID"]),});
                            if (SqlHelper.HasError)
                            {
                                MyBox.ShowWarning(SqlHelper.Message, "Yêu Cầu Thanh Lý");
                            }

                            var lichsuDa = new TBL_lichsuDA();
                            lichsuDa.Add(new TBL_lichsu
                            {
                                idthietbi = (int)dr["ID"],
                                ngay = MyLogin.Original.Date,
                                nguoiTH = MyLogin.Original.hoten,
                                noidung = "Yêu Cầu Thanh Lý"
                            });
                        }

                        OnSaveChanging(new SaveChangingEventArgs(i, dtTL.Rows.Count));
                    }


            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Yêu cầu thanh lý");
            }

            NotSave = false;
            OnSaveComplete(null);
            Cursor.Current = current;
            Enabled = true;
        }

        private void gbDesc_DoubleClick(object sender, EventArgs e)
        {
            DataTable table = dsThietBi.TBL_THIETBI;
            int[] rows = gbDesc.GetSelectedRows();
            for (int i = rows.Length; i > 0; i--)
            {
                DataView dv = dsThietBi.TBL_THIETBI.DefaultView;
                DataRow dr = gbDesc.GetDataRow(rows[i - 1]);
                if (dv != null)
                {
                    dv.RowFilter = "ID=" + dr["ID"];
                    if (dv.Count == 0)
                    {
                        table.ImportRow(dr);
                    }
                    gbDesc.DeleteRow(rows[i - 1]);
                    dv.RowFilter = "";
                }
            }
        }

        public void Cancel()
        {
            dsThietBi.RejectChanges();
            NapCTL();
            NotSave = false;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Nap();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }


        public void MoveData()
        {
            var dv = gbDesc.DataSource as DataView;
            DataView dvv = dsThietBi.TBL_THIETBI.DefaultView;
            if (dvv != null)
            {
                dvv.RowFilter = "Selected=1";
                DataTable table = dv.Table;
                for (int i = table.Rows.Count; i > 0; i--)
                {
                    DataRow dr = table.Rows[i - 1];
                    dv.RowFilter = "ID=" + dr["ID"];
                    if (dv.Count == 0)
                    {
                        table.ImportRow(dr);
                        table.Rows.RemoveAt(i - 1);
                    }
                    dv.RowFilter = "";
                }
                dvv.RowFilter = "";
            }
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            gbList_DoubleClick(gbList, e);
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            gbDesc_DoubleClick(gbDesc, e);
        }

        private void btnAllRight_Click(object sender, EventArgs e)
        {
            gbList.SelectAll();
            gbList_DoubleClick(gbList, e);
        }

        private void btnAllLeft_Click(object sender, EventArgs e)
        {
            gbDesc.SelectAll();
            gbDesc_DoubleClick(gbDesc, e);
        }

        private void btIn_Click(object sender, EventArgs e)
        {
            var adapter = new CanThanhLyTableAdapter();
            adapter.Connection.ConnectionString = DbHelper.ConnectionString;
            var rpt = new rptThanhLyOrder(adapter.GetData(txtDonvi.EditValue as int?), gbDesc.ActiveFilterString);
            rpt.ShowPreview();
        }
    }
}